package com.zlsy.thread.future;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author zhouliang
 * @date 2020/10/12 20:21
 * 演示get方法过程中抛出异常
 * for循环为了演示抛出exception的时机，并不是说一产生异常就抛出，直到我们执行的时候，才会抛出；
 */
@Slf4j
public class GetException {

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(20);
        //提交任务的时候就算子线程已经执行了并且抛出了异常你也是感知不到的；
        Future<Integer> future = service.submit(new CallableTask());
        try {
            TimeUnit.SECONDS.sleep(3);
            //只有在get的时候才能感知到子线程的异常
            log.info("isDone: {}", future.isDone());
            Integer integer = future.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            log.error("InterruptedException:", e);
        } catch (ExecutionException e) {
            //无论你在子线程里面抛出什么异常，在get这里捕获到的都是ExecutionException
            log.error("ExecutionException:", e);
        } finally {
            service.shutdown();
        }
    }

    static class CallableTask implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            throw new IllegalArgumentException("Callable抛出异常");
        }
    }
}
